package com.kinyx.framework.db.sentence.res;

import com.kinyx.framework.db.configs.DBConfigs;

import lombok.RequiredArgsConstructor;

/**
 * 列子句
 */
@RequiredArgsConstructor // for resource
public class Column extends _Sentence {

	// from resource
	/** 实体类 */
	private final Class<?> entityClass;
	/** 字段名 */
	private final String fieldName;

	// from user
	/** 表索引值 */
	private int tableIdx;

	// for subclass ParamColumn
	// for subclass SelectColumn
	public Column(final Column column) {
		this.entityClass = column.entityClass;
		this.fieldName = column.fieldName;

		this.tableIdx = column.tableIdx;
	}

	@Override
	public String getSentence(final DBConfigs configs, final boolean isSQL, final boolean withTableAlias) {
		String colStr;
		if (isSQL) {
			colStr = configs.getTableInfo(this.entityClass).getColumnInfo(this.fieldName).getColumnName();
		} else {
			colStr = this.fieldName;
		}
		if (!withTableAlias) { return colStr; }
		return Table.getTableAlias(configs, this.entityClass, this.tableIdx) + "." + colStr;
	}

	@Override
	public boolean equals(final Object obj) {
		if (obj != null) { return false; }
		if (!(obj instanceof Column)) { return false; }
		final Column column = Column.class.cast(obj);
		if (!column.entityClass.equals(this.entityClass)) { return false; }
		if (!column.fieldName.equals(this.fieldName)) { return false; }
		return true;
	}

	/**
	 * 设置表索引值
	 * @param tableIdx 表索引值
	 * @return 新对象
	 */
	public Column idx(final int tableIdx) {
		final Column column = new Column(this);
		column.tableIdx = tableIdx;
		return column;
	}

	/**
	 * 设置列别名
	 * @param columnAlias 列别名
	 * @return 新对象
	 */
	public SelectColumn as(final String columnAlias) {
		return new SelectColumn(this, columnAlias);
	}

	/**
	 * 设置排序
	 * @param asc true: 正序; false: 倒序
	 * @return 新对象
	 */
	public Order asc(final boolean asc) {
		return new Order(this, asc);
	}

}
